﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace DigiMate
{
	class RssXmlReader : XmlTextReader
	{
		private bool readingDate = false;
		const string CustomUtcDateTimeFormat = "ddd MMM d yyyy H:mm:ss 'UTC'"; // Wed Oct 07 08:00:07 GMT 2009

		public RssXmlReader(Stream s) : base(s) { }

		public RssXmlReader(string inputUri) : base(inputUri) { }

		public override void ReadStartElement()
		{
			if (string.Equals(base.NamespaceURI, string.Empty, StringComparison.InvariantCultureIgnoreCase) &&
				(string.Equals(base.LocalName, "lastBuildDate", StringComparison.InvariantCultureIgnoreCase) ||
				string.Equals(base.LocalName, "pubDate", StringComparison.InvariantCultureIgnoreCase)))
			{
				readingDate = true;
			}
			base.ReadStartElement();
		}

		public override void ReadEndElement()
		{
			if (readingDate)
			{
				readingDate = false;
			}
			base.ReadEndElement();
		}

		public override string ReadString()
		{
			if (readingDate)
			{
				CultureInfo en = new CultureInfo("en-US");
				string dateString = base.ReadString().Trim();
				DateTime dt;
				if (!DateTime.TryParse(dateString, en, DateTimeStyles.AssumeUniversal, out dt))
					dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, en);
				return dt.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture);
			}
			else
			{
				return base.ReadString();
			}
		}
	}
}
